package com.oceansoft.mobile.econsole.modules.mappoint.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.oceansoft.mobile.econsole.common.util.HttpClientUtil;
import com.oceansoft.mobile.econsole.modules.base.entity.ApiPager;
import com.oceansoft.mobile.econsole.modules.base.entity.Query;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import com.oceansoft.mobile.econsole.modules.mappoint.entity.MapPoint;
import com.oceansoft.mobile.econsole.modules.mappoint.persistence.IMapPointMapper;
import com.oceansoft.mobile.econsole.modules.mappoint.service.IMapPointService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by Administrator on 2016/2/17.
 */
@Service
public class MapPointServiceImpl implements IMapPointService {

    @Resource
    private IMapPointMapper mapPointMapper;

    @Override
    @Transactional
    public Result coordinateTransformation() {
        List<MapPoint> list = mapPointMapper.queryInitMapPoint();
        if(list != null){
            // 调用百度API，坐标转换，并更新数据库
            for (MapPoint e : list){

                try {
                    String result = HttpClientUtil.doGet("http://api.map.baidu.com/geoconv/v1/?coords="+e.getSmx()+","+e.getSmy()+"&ak=33dD3XEvXrMws5lsVx7wKGGa&output=json&from=1&to=5");
                    JSONObject json = JSONObject.fromObject(result);
                    JSONArray array = JSONArray.fromObject(json.get("result"));
                    JSONObject o = JSONObject.fromObject(array.get(0));
                    e.setLongitude(o.get("x").toString());
                    e.setLatitude(o.get("y").toString());

                    mapPointMapper.updateMapPoint(e);

                }catch (Exception ex){
                    ex.printStackTrace();
                    return new Result(Result.FAILURE);
                }

            }
        }
        return new Result(Result.SUCC,"坐标转换成功");
    }

    @Override
    public ApiPager getMapInterest(Query query) {

        PageHelper.startPage(query.getPageNum(), query.getNumPerPage(), true);
        Page<MapPoint> page = (Page<MapPoint>) mapPointMapper.queryMapPointByCondition(query);//搜索条件普通坐标改为百度坐标进行搜索
        ApiPager<MapPoint> apiPager = new ApiPager<MapPoint>(query.getNumPerPage(),query.getPageNum(),page.getTotal(),page.getResult());
        return apiPager;

    }
}
